package top.lixunda.common.validate.validate;

import top.lixunda.common.validate.annotation.XumIncludes;
import top.lixunda.common.validate.core.ValidateError;
import top.lixunda.common.validate.exception.XumValidException;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * @author Xumda
 * @version time:2019/12/9 13:15
 */
public class IncludesValidate implements AnnotationValidate {

    @Override
    public boolean support(Class annotationClass) {
        return XumIncludes.class.equals(annotationClass);
    }

    @Override
    public ValidateError valid(Annotation annotation, Field field, Object obj, Object value, AnnotationCacheValidate handler) {
        XumIncludes a = (XumIncludes) annotation;
        boolean isNull = (value == null || (value instanceof String && "".equals(value)));
        if (isNull) {
            return null;
        }
        if (a.value().length > 0) {
            if (value instanceof String) {
                for (String item : a.value()) {
                    if (item.equals(String.valueOf(value))) {
                        return null;
                    }
                }
            } else {
                throw new XumValidException("value值必须为String类型，或者不要设置value数组,使用注解中的其他数组");
            }
        } else if (a.numbers().length > 0) {
            if (value instanceof Short || value instanceof Integer || value instanceof Long) {
                long num = ValidatorPrivateUtils.getLongFromNumber(value);
                for (long item : a.numbers()) {
                    if (item == num) {
                        return null;
                    }
                }
            } else {
                throw new XumValidException("value值必须为String类型，或者不要设置value数组,使用注解中的其他数组");
            }
        } else {
            throw new XumValidException("请根据参数类型选择一个数组设置可选择的值");
        }
        return new ValidateError(getErrorMessage(a.message(), field, value));
    }

    private String getErrorMessage(String message, Field field, Object value) {
        return "".equals(message)
                ? field.getName() + "必须从规定的常量中进行选择"
                : message.replaceAll("#value#", String.valueOf(value)).replaceAll("#name#", field.getName());
    }

}
